import { requestApi } from '../../../api'
import { formatImage } from '../../../utils/formatImage'
import { formatPrice, throttle } from '../../../utils/util'

const app = getApp()

Page({
  data: {
    winHeight: 0,
    spuNo: '',

    // 图片预览关闭时会出发page onShow事件
    previewImageFlag: false,

    // “show”、“推荐” 列表： 接口使用
    // spu类型: 1 主力 2系列
    spuType: 1,

    // “心愿单”：接口使用 
    // spu类型 1:商主。2:运主。3:系列
    // 主力详情接口type字段 重置 spuTypeForFavorite值
    spuTypeForFavorite: 2,

    // spu 详情
    spuInfo: {},
    infoImageScroll: '',

    // 预约到货---挂载的货号列表 浮层标识
    spuMountedListLayerFlag: false,

    // 主力spu挂载的货号spu列表
    spuMountedList: [],

    // "简介"模块
    summaryInfo: {},

    // “购买”模块--商品列表
    goodsList: {},

    // 商品浮层标识
    goodsLayerFlag: false,

    goodsAllList: [],
    goodsQuery: {},
    oldGoodsQuery: {
      page: 1,
      count: 20,
      noMore: false,
    },

    // “查看更多商品”浮层--滚动状态
    // 当商品浮层显示时，页面级scroll-y不允许纵向滚动，
    // 解决浮层的滚动导致页面穿透问题（页面跟着滚动）
    goodsScrollY: false,

    // show 瀑布流
    showList: {},

    // 请求状态，限制频繁请求
    // 预约到货/心愿单/点赞请求状态
    subscribeRequestFlag: false,
    favoriteRequestFlag: false,
    praiseRequestFlag: false,

    // “推荐” 瀑布流
    recommendList: [],
    page: 1,
    count: 80,
    noMore: false,
  
    // 导航模块
    navFixed: false,
    navId: 'nav',
    navHeight: 0,
    navItemIds: ['intro', 'buy', 'show', 'recommend'],
    switchNavItemId: 'intro',

    // scrollTop超过该元素，nav即悬浮
    navReferElementClass: 'info_swiper',
  },

  onLoad(options) {
    // app端二维码分享
    if (options.scene && options.scene.length) {
      const scene = decodeURIComponent(options.scene)
      const paramArr = scene.split(',')

      if (paramArr[1] == 'sl') {
        app.shortUrlToLong(paramArr[0], res => {
          this.data.spuNo = res.spu_no

          if (res.channel) {
            app.data.channel = res.channel
          }
        })
      } else {
        this.data.spuNo = paramArr[0]

        if (paramArr[1]) {
          app.data.channel = paramArr[1]
        }
      }
    } else {
      this.data.spuNo = options.spu_no
    }

    let systemInfo = {}

    try {
      systemInfo = wx.getSystemInfoSync()
    } catch (e) {
      // Do something when catch error
    }

    this.setData({
      winHeight: systemInfo.windowHeight,
    })
  },

  // 页面出现在前台时执行
  onShow() {
    // 如果是关闭图片预览导致的onShow事件，则不重新加载页面
    if (this.data.previewImageFlag) {
      this.data.previewImageFlag = false

      return 
    }

    wx.showLoading({
      title: '加载中...',
    })

    // 页面从后台切换到前台、页面栈返回，更新spu详情相关状态（收藏、点赞等）
    this.getSpuDetail()
  },

  // 格式化“点赞数”
  formatLikeCount(count) {
    const units = ['k', 'w']
    const pointLength = 1
    let unit = ''
    let size = count
    
    while (size >= 1000 && (unit = units.shift())) {
      size = size / 1000
    }

    return (unit === '' ? size : size.toFixed(pointLength).replace(/\.0$/, '')) + unit
  },

  // 获取SPU详情
  getSpuDetail() {
    app.request({
      url: requestApi.getMainSpuDetail,
      login: false,
      data: {
        spu_no: this.data.spuNo
      },
    }, res => {
      const data = res.original.data
      const spuInfo = data.spu_info
      const summaryInfo = data.summary_info || {}
      const goodsList = data.goods_list || {}
      const showList = data.show_list || {}

      // 主力类型 1 商主 2 运主
      this.data.spuTypeForFavorite = spuInfo.type

      // 是否已收藏心愿单
      spuInfo.is_favorite_spu = !!spuInfo.is_favorite_spu;

      if (spuInfo && spuInfo.length > 0) {
            spuInfo.detail_image_list.forEach(item => {
            item.path_full = formatImage.cdnImage(item.path, formatImage.THUMBNAIL_L)
          })
      }

      spuInfo.goods_price_format = formatPrice(spuInfo.goods_price / 100)

      if (goodsList.list && goodsList.list.length > 0) {
        goodsList.list.forEach(item => {
          item.goods_price_format = formatPrice(item.goods_price / 100)
          item.product_cover_image.path_full = formatImage.cdnImage(item.product_cover_image.path, formatImage.THUMBNAIL_L)
        })
      }

      if (showList.list && showList.list.length) {
        showList.list.forEach(item => {
          item.avatar_full = formatImage.cdnImage(item.avatar, formatImage.THUMBNAIL_L)
          item.cover_image.path_full = formatImage.cdnImage(item.cover_image.path, formatImage.THUMBNAIL_L)

          item.is_favorite = !!item.is_favorite
          item.new_liked_amount = this.formatLikeCount(item.liked_amount)

          // 短视频
          if (item.square_cover_image) {
            item.square_cover_image.path_full = formatImage.cdnImage(item.square_cover_image.path, formatImage.THUMBNAIL_L)
          }
        })
      }

      // 修改页面标题
      wx.setNavigationBarTitle({
        title: spuInfo.name_e,
      })

      this.setData({
        spuInfo,
        summaryInfo,
        showList,
        goodsList,
      })

      if (this.data.recommendList.length === 0) {
        // 获取“推荐”瀑布流
        this.getRecommendData()
      }
    }, error => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      wx.hideLoading()
    })
  },

  // spu 详情图滚动
  changeCoverSwiper: function (e) {
    this.setData({
      infoImageScroll: `cover${e.detail.current}`
    })
  },

  // spu 详情图预览
  previewImage: function (e) {
    const imgList = this.data.spuInfo.detail_image_list.map(item => item.path_full)

    wx.previewImage({
      urls: imgList,
      current: imgList[e.currentTarget.dataset.index],

      success: () => {
        // 图片预览关闭时会出发page onShow事件
        // 将previewImageFlag置为true，onShow事件不重新加载页面数据
        this.data.previewImageFlag = true
      },
    })
  },

  // 预约到货---获取预约货号列表
  onSubscribeGoods() {
    if (!app.toLogin()) return

    // spu_subscription_status: 1 可预约 2 已预约
    if (this.data.spuInfo.spu_subscription_status === 2) {
      this.showTips('已预约', '商品到货后，会在OFashion迷橙APP消息中心通知您。')

      return
    } 

    if (this.data.subscribeRequestFlag) return

    this.data.subscribeRequestFlag = true

    const params = {
      spu_no: this.data.spuNo,
    }

    app.request({
      url: requestApi.getMainSpuMountedArtList,
      login: true,
      data: params,
    }, res => {
      const list = res.original.data.item_list || []

      // gender_id: 款式ID，0:不区分，1:男款，2：女款，3：男女同款；4：男童；5：女童；6：童同款
      const gender = ['', '男款', '女款', '男女同款', '男童', '女童', '童同款']

      list.forEach(item => {
        item.cover_image.path_full = formatImage.cdnImage(item.cover_image.path, formatImage.THUMBNAIL_L)
        item.gender_name = gender[item.gender_id]
        item.is_checked = false
      })
      
      this.setData({
        spuMountedList: list,
        spuMountedListLayerFlag: true,
      })
    }, error => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      this.data.subscribeRequestFlag = false
    })
  },

  // 关闭spu货号列表浮层
  onCloseSpuMountedList() {
    this.setData({
      spuMountedListLayerFlag: false,
    })
  },

  // 预约到货--spu选项 选中/取消状态
  onCheckMountedSpuList(e) {
    const index = e.currentTarget.dataset.index

    this.setData({
      [`spuMountedList[${index}].is_checked`]: !this.data.spuMountedList[index].is_checked,
    })
  },

  // 预约到货--确定（预约到货提醒）
  onConfirmMountedSpuList() {
    if (!app.toLogin()) return

    const aspuNoArr = []

    this.data.spuMountedList.forEach(item => {
      if (item.is_checked) {
        aspuNoArr.push(item.aspu_no)
      }
    })

    if (aspuNoArr.length === 0) return 

    if (this.data.subscribeRequestFlag) return

    this.data.subscribeRequestFlag = true

    const params = {
      mspu_no: this.data.spuNo,
      aspu_no: aspuNoArr,
    }

    app.request({
      url: requestApi.subscribeArtSpuRemind,
      method: 'POST',
      login: true,
      data: params,
    }, res => {
      this.showTips('预约成功', '商品到货后，会在OFashion迷橙APP消息中心通知您。')

      // spu_subscription_status: 1 可预约 2 已预约
      this.setData({
        ['spuInfo.spu_subscription_status']: 2,
        spuMountedListLayerFlag: false,
      })
    }, error => {
      this.showTips('预约失败，请重新预约')
    }, () => {
      this.data.subscribeRequestFlag = false
    })
  },

  // 取消/收藏SPU心愿单
  onFavoriteSpu() {
    if (!app.toLogin()) return

    if (this.data.favoriteRequestFlag) return

    this.data.favoriteRequestFlag = true
  
    // 心愿单当前状态
    // 已收藏 ture，未收藏 false
    const status = this.data.spuInfo.is_favorite_spu
    const url = status ? requestApi.cancelFavoriteSpu : requestApi.setFavoriteSpu

    // spu类型 1:商主。2:运主。3:系列
    const params = {
      spu_no: this.data.spuNo,
      spu_type: this.data.spuTypeForFavorite,
    }

    app.request({
      url,
      method: 'POST',
      login: true,
      data: params,
    }, () => {
      this.setData({
        'spuInfo.is_favorite_spu': !this.data.spuInfo.is_favorite_spu,
      })

      const { title, msg } = {
        title: status ? '已从心愿单移除' : '添加心愿单成功',
        msg: status ? '' : '可在"我的"-"心愿单"里查看',
      }

      this.showTips(title, msg)
    }, error => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      this.data.favoriteRequestFlag = false
    })
  },

  // 取消/点赞：买家秀/短图文/短视频
  onPraiseShow(e) {
    if (!app.toLogin()) return

    if (this.data.praiseRequestFlag) return

    this.data.praiseRequestFlag = true

    const feedId = e.currentTarget.dataset.feedId
    const list = this.data.showList.list
    let item = null
    let itemIndex = 0

    // 遍历获取show点赞卡片、瀑布流索引
    for (let i = 0; i < list.length; i++) {
      if (list[i].feed_id === feedId) {
        item = list[i]

        break
      }
    }

    // 当前状态 已点赞 ture，未点赞 false
    const status = item.is_favorite
    const params = {}
    let url = ''

    // 短图文、短视频 属于社区内容，其使用的点赞接口 与买家秀点赞接口 不一致
    // feed_type: feed类型 2短图片，3短视频，11用户买家秀
    if (item.feed_type === 11) {
      url = status ? requestApi.cancelLikeBuyerShow : requestApi.setLikeBuyerShow
      params.comment_id = feedId
    } else {
      url = status ? requestApi.cancelLikeCommunityContent : requestApi.likeCommunityContent
      params.feed_id = feedId
    }

    app.request({
      url,
      data: params,
    }, () => {
      // 更新 点赞状态、点赞数
      item.liked_amount = status ? item.liked_amount - 1 : item.liked_amount + 1

      this.setData({
        [`showList.list[${itemIndex}].new_liked_amount`]: this.formatLikeCount(item.liked_amount),
        [`showList.list[${itemIndex}].is_favorite`]: !item.is_favorite,
      })
    }, (error) => {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false,     
      })
    }, () => {
      this.data.praiseRequestFlag = false
    })
  },

  // 跳转到“主力spu详情页”
  toMainSpuDetail(e) {
    const spuNo = e.currentTarget.dataset.spuNo

    wx.navigateTo({
      url: `../../mainSpu/mainSpuDetail/mainSpuDetail?spu_no=${spuNo}`
    })
  },

  // 跳转到“系列spu详情页”
  toSerialSpuDetail(e) {
    const spuNo = e.currentTarget.dataset.spuNo

    wx.navigateTo({
      url: `../../serialSpu/serialSpuDetail/serialSpuDetail?spu_no=${spuNo}`
    })
  },

  // 跳转到“show详情页”
  toShowDetail(e) {
    const feedId = e.currentTarget.dataset.feedId

    wx.navigateTo({
      url: `../../spuShow/detail/detail?feed_id=${feedId}`
    })
  },

  // 跳转到“show列表页”
  toShowList() {
    // spu类型 1 主力 2系列
    wx.navigateTo({
      url: `../../spuShow/list/list?spu_no=${this.data.spuNo}&spu_type=${this.data.spuType}`
    })
  },

  // 获取推荐列表
  getRecommendData() {
    const params = {
      spu_no: this.data.spuNo,
      spu_type: this.data.spuType,
      start: (this.data.page - 1) * this.data.count,
      count: this.data.count,
    }

    app.request({
      url: requestApi.getSpuDetailRecommendList,
      login: false,
      data: params,
    }, res => {
      const data = res.original.data

      // 没有更多
      if (data.item_list.length < this.data.count) {
        this.data.noMore = true
      }

      if (data.item_list.length === 0) return

      // 系列spu 展示的最大图片数
      const maxImageCount = 4

      data.item_list.forEach(item => {
        item.goods_price_format = formatPrice(item.goods_price  / 100)
        item.top_image.path_full = formatImage.cdnImage(item.top_image.path, formatImage.THUMBNAIL_L)
        
        // 兼容：系列spu类型有该字段
        if (!item.image_list) {
          item.image_list = []
        }

        const imageLength = item.image_list.length

        if (imageLength > 0) {
          item.image_list.forEach(image => {
            image.path_full = formatImage.cdnImage(image.path, formatImage.THUMBNAIL_L)
          })
          
          item.new_image_list = item.image_list

          // 展示剩余图片数（主力spu数）
          item.remain_count = 0

          if (imageLength > maxImageCount) {
            // 展示的图片列表 不超过maxImageCount
            item.new_image_list = item.new_image_list.slice(0, maxImageCount)

            // 最后一张图有蒙层，所以剩余图片数+1
            item.remain_count = imageLength - maxImageCount + 1
          }
        }
      })

      this.setData({
        [`recommendList[${this.data.page - 1}]`]: data.item_list,
      })
    }, error => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    })
  },

  // “推荐”加载更多
  scrollToLower() {
    if (this.data.noMore) return

    this.data.page = this.data.page + 1

    this.getRecommendData()
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: `${this.data.spuInfo.name_e} ${this.data.spuInfo.spu_name}`,
      path: `/spu-pages/mainSpu/mainSpuDetail/mainSpuDetail?spu_no=${this.data.spuNo}`,
      imageUrl: this.data.spuInfo.detail_image_list[0].path_full,
    }
  },

  // 查看更多商品
  openSpuGoods() {
    this.setData({
      goodsScrollY: !this.data.goodsLayerFlag,
      goodsLayerFlag: !this.data.goodsLayerFlag
    })

    if (!this.data.goodsLayerFlag) return

    // 重置参数、商品列表
    this.data.goodsQuery = {
      ...this.data.oldGoodsQuery,
    }
    this.data.goodsAllList = []
    this.getSpuGoodsList()
  },

  scrollGoodsToLower() {
    if (this.data.goodsQuery.noMore) {
      // wx.showToast({
      //   title: '没有更多了',
      //   icon: 'none',
      //   duration: 2000,
      // })

      return
    }

    this.data.goodsQuery.page = this.data.goodsQuery.page + 1

    this.getSpuGoodsList()
  },

  // 全部商品瀑布流
  getSpuGoodsList() {
    wx.showLoading({
      title: '加载中...',
    })

    app.request({
      url: requestApi.getSpuGoodsList,
      login: false,
      data: {
        spu_no: this.data.spuNo,
        start: (this.data.goodsQuery.page - 1) * this.data.goodsQuery.count,
        count: this.data.goodsQuery.count,
      },
    }, data => {
      const goodsAllList = data.original.data.item_list || []

      // 没有更多
      if (goodsAllList.length < this.data.goodsQuery.count) {
        this.data.goodsQuery.noMore = true
      }

      if (goodsAllList.length === 0) return

      goodsAllList.forEach(item => {
        item.goods_price_format = formatPrice(item.goods_price / 100)
        item.product_cover_image.path_full = formatImage.cdnImage(item.product_cover_image.path, formatImage.THUMBNAIL_M)
      })

      this.setData({
        goodsAllList: this.data.goodsAllList.concat(goodsAllList),
      })
    }, error => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      wx.hideLoading()
    })
  },

  // 显示导航栏
  showNav() {
    const query = wx.createSelectorQuery()

    query.select(`.${this.data.navReferElementClass}`).boundingClientRect()
    query.exec(res => {
      this.setData({
        navFixed: this.data.scrollTop > res[0].height,
      })
    })
  },

  // 导航栏高度
  setNavHeight() {
    if (!this.data.navHeight && this.data.navFixed) {
      const query = wx.createSelectorQuery()

      query.select(`#${this.data.navId}`).boundingClientRect(rect => {
        this.data.navHeight = rect.height
      }).exec()
    }
  },

  // 页面滚动，定位导航栏位置
  scrollPage: throttle(function (res) {
    this.data.scrollTop = res[0].detail.scrollTop

    // 显示导航栏
    this.showNav()
    this.setNavHeight()

    const query = wx.createSelectorQuery()
    let switchNavItemId = ''

    this.data.navItemIds.forEach(item => {
      query.select(`#${item}`).boundingClientRect()
    })

    query.exec(rects => {
      for (let i = 0, len = rects.length; i < len; i++) {
        const rect = rects[i]

        // navItemIds 里的导航项会有不存在情况
        // res (4) [{…}, {…}, null, {…}]
        if (rect && rect.id && rect.height + rect.top - this.data.navHeight > 1) {
          this.setData({
            switchNavItemId: rect.id,
          })

          break
        }
      }
    })
  }, 100, 300),

  // 切换导航栏，滑动页面到指定位置
  switchNav(e) {
    const id = e.target.dataset.id

    if (!id) return

    // 为了解决页面抖动，在页面scroll时，并未重置scrollTop；
    // 此时重置页面scrollTop，使切换nav时，能正确滑动到指定位置
    this.setData({
      scrollTop: this.data.scrollTop,
    })

    const query = wx.createSelectorQuery()

    query.select(`#${id}`).boundingClientRect()
    query.exec(res => {
      this.setData({
        switchNavItemId: id,
        scrollTop: this.data.scrollTop + res[0].top - this.data.navHeight,
      })
    })
  },

  // 提示浮层
  showTips(title, msg = '', time = 3) {
    this.setData({
      tips: {
        title,
        msg,
        visible: true,
      }
    })

    setTimeout(() => {
      this.setData({
        'tips.visible': false,
      })
    }, 3000)
  },
})
